/*
 * @Author: zi.yang
 * @Date: 2022-12-03 20:05:58
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-12-04 02:31:25
 * @Description: rollup.config.js
 * @FilePath: /promise/rollup.config.js
 */
/* eslint-disable no-console */
import path from 'path';
import { watch } from 'rollup';
import sourceMaps from 'rollup-plugin-sourcemaps';
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';

import commonjs from '@rollup/plugin-commonjs';

const isProd = process.env.BUILD === 'production';
const moduleName = 'ToyPromise';
const override = { compilerOptions: { module: 'ESNext' } };
const resolve = (type) => path.resolve(__dirname, `./dist/toy-promise.${type}.js`);

const options = {
  input: './lib/index.ts',
  plugins: [
    typescript({
      tsconfig: './tsconfig.json',
      tsconfigOverride: override,
    }),
    commonjs(),
  ],
  output: [
    {
      format: 'cjs',
      file: resolve('cjs'),
      name: moduleName,
    },
    {
      format: 'esm',
      file: resolve('esm'),
      name: moduleName,
    },
    {
      format: 'umd',
      file: resolve('umd'),
      name: moduleName,
    },
    {
      format: 'iife',
      file: resolve('iife'),
      name: moduleName,
    },
  ],
};

if (!isProd) {
  const watchOptions = {
    ...options,
    plugins: [
      typescript({
        tsconfig: './tsconfig.json',
        tsconfigOverride: override,
      }),
    ],
    watchOptions: {
      include: 'lib/**',
      exclude: 'node_modules/**',
    },
  };
  const watcher = watch(watchOptions);
  watcher.on('event', (event) => {
    switch (event.code) {
      case 'START':
        console.time('buildTime');
        console.info('Rebuilding...');
        break;
      case 'END':
        console.timeEnd('buildTime');
        console.info('Rebuild Done!');
        break;
      case 'ERROR':
        console.error('Rollup error: ', event);
        break;
      default:
        break;
    }
  });
}

if (isProd) {
  options.plugins.push(...[sourceMaps()]);
  options.output = options.output.reduce((prev, cur) => {
    prev.push({
      ...cur,
      sourcemap: true,
    });
    // min.js
    prev.push({
      ...cur,
      file: cur.file.replace(/\.js$/, '.min.js'),
      sourcemap: true,
      plugins: [terser()],
    });
    return prev;
  }, []);
}

export default options;
